package mobi.greenplate.client.service;

import mobi.greenplate.client.connect.ConnectionContext;
import mobi.greenplate.client.connect.ServerCall;
import mobi.greenplate.client.connect.ServerCallBuilder;

/**
 *
 * @author dmakariev
 */
public abstract class AbstractBaseService {

    public AbstractBaseService(ConnectionContext connectionContext, String serviceName) {
        this.connectionContext = connectionContext;
        this.serviceName = serviceName;
        this.serviceUrl="http://"+connectionContext.getServerName()+":"+connectionContext.getServerPort()+"/services/"+serviceName+"/";
    }
    
    private final ConnectionContext connectionContext;
    private final String serviceName;
    private final String serviceUrl;

    protected String getServiceUrl(){
        return serviceUrl;
    }

    protected String getOwnedByServiceUrl(Long ownerId){
        return "http://"+connectionContext.getServerName()+":"+connectionContext.getServerPort()+"/services/user/"+ownerId+"/";
    }

    protected String getUrlById(Long id){
        return getServiceUrl()+id;
    }

    protected String getUrlOwnedById(Long ownerId, Long id){
        return getOwnedByServiceUrl(ownerId)+serviceName+"/"+id;
    }

    protected String getPagedUrl(int first, int max){
        return getServiceUrl()+"?first="+first+"&max="+max;
    }
    
    protected ServerCall call(){
        return new ServerCallBuilder(this.connectionContext);
    }

   //assertEquals("object was created", 201, statusCode);

    protected boolean assertCreated(int statusCode){
        return assertTrue(201==statusCode," STATUS CODE:"+statusCode+" COULD NOT CREATE url="+getServiceUrl());
    }

    protected boolean assertExist(int statusCode, Long id){
        return assertExist(statusCode,getUrlById(id));
    }

    protected boolean assertExist(int statusCode, String url){
        return assertTrue(200==statusCode," STATUS CODE:"+statusCode+" COULD NOT GET or UPDATE url="+url);
    }

    protected boolean assertDeleted(int statusCode, Long id){
        return assertTrue(204==statusCode," STATUS CODE:"+statusCode+" COULD NOT DELETE url="+getUrlById(id));
    }

    protected boolean assertTrue(boolean shouldBeTrue, String message){
        if(false==shouldBeTrue){
            throw new RuntimeException(this.getClass().getName()+":"+message);
        }
        return true;
    }
    

}
